
package com.zshan.clinic.web.netty.manager;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class ChannelManager {
    private static final Map<Long, Channel> clinicMap = new ConcurrentHashMap<>();
    private static final Map<Channel, Long> channelMap = new ConcurrentHashMap<>();

    public static void add(Long clinicId, Channel channel) {
        clinicMap.put(clinicId, channel);
        channelMap.put(channel, clinicId);
    }

    public static void remove(Channel channel) {
        Long clinicId = channelMap.remove(channel);
        if (clinicId != null) {
            clinicMap.remove(clinicId);
        }
    }

    public static Long getClinicId(Channel channel) {
        return channelMap.get(channel);
    }

    /**
     * 给客户端发送消息
     * @param clinicId
     * @param message
     */
    public static void sendToClinic(Long clinicId, String message) {
        Channel ch = clinicMap.get(clinicId);
        if (ch != null && ch.isActive()) {
            log.info("给客户端发送的消息，通道ID:{},诊所ID:{},内容:{}",ch.id(),clinicId,message);
            ch.writeAndFlush(new TextWebSocketFrame(message));
        }
    }

    /**
     * 广播消息
     * @param message
     */
    public static void broadcast(String message) {
        for (Channel ch : clinicMap.values()) {
            if (ch.isActive()) {
                ch.writeAndFlush(new TextWebSocketFrame(message));
            }
        }
    }
}
